// pages/mine/myMessage/myMessage.js
const app = getApp()
const db = wx.cloud.database()
const _ = db.command
const MessageDB = db.collection('messageData')
const publishDB = db.collection('publishData')
const userinfoDB = db.collection('userInfo')
Page({

  currentPage: 1,
  pageSize: 15,
  totalPage: 0,

  /**
   * 页面的初始数据
   */
  data: {
    myMessage: [],
    // status:true ,//true为正常显示，false为显示删除按钮
    messageHidden: "",
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //全局变量  直接获取  当然要首先在我的登陆才会有数据
    //我的所有留言根据 userID获取 也就是openID
    let that = this
    console.log(app.globalData.userOpenid)
    console.log("currentPage", that.currentPage)
    console.log("pageSize", that.pageSize)
    that.getTotalPage()
    that.getListData()

  },

  //获取总页数
  getTotalPage:function(){
    var that=this
    MessageDB.where({
      messageID: app.globalData.userOpenid
    }).count().then(res => {
      console.log("counts", res.total)
      let counts = res.total
      that.totalPage = counts === 0 ? 0 : counts <= that.pageSize ? 1 : counts % that.pageSize == 0 ? parseInt(counts / that.pageSize) : parseInt(counts / that.pageSize) + 1
      console.log("totalPage:", that.totalPage)
      })
  },

  //获取留言列表数据
  getListData:function(){
    var that=this
    MessageDB.where({
      messageID: app.globalData.userOpenid
    }).orderBy('messageDate', 'desc')//先根据日期倒序，再根据id顺序
      .skip((that.currentPage - 1) * that.pageSize)
      .limit(that.pageSize)
      .get({
        success: function (res) {
          console.log("查询成功", res)
          if (res.data.length == 0) {
            that.setData({
              myMessage:[],
              messageHidden: "你还没有留言，快去围观公告吧！"
            })
          } else {
            let index=that.currentPage-1
            that.setData({
              ['myMessage['+index+']']:res.data,
              // messageHidden: true
            })
          }
          console.log("myMessage:",that.data.myMessage)
        }, fail: function (res) {
          wx.showToast({
            title: '系统出错',
            icon: "none"
          })
        }
      })
  },

  handlescrollbottom:function(){
    console.log("触底函数")
    var that = this
    if (that.currentPage >= that.totalPage) {
      wx.showToast({
        title: '亲,没有更多留言了',
        icon: 'none',
        duration: 2000
      })
    } else {
      that.currentPage++
      that.getListData()
    }
  },

  //跳转详情页
  clickNavDetail: function (e) {
    console.log(e.currentTarget.id)
    let that = this
    publishDB.where({
      publishID: e.currentTarget.id
    }).get({
      success: function (res) {
        console.log("公告数据：", res.data[0])
        let _item = res.data[0]
        userinfoDB.where({
          _openid: res.data[0].promulgatorID
        }).get({
          success: function (res) {
            console.log("用户信息", res.data)
            _item['userinfo'] = res.data
            let item = JSON.stringify(_item)
            console.log(item)
            wx.navigateTo({
              url: '/pages/home/publishDetail/publishDetail?item=' + item
            })
          }, fail: function (res) {
            console.log("查询出错")
          }
        })
      }, fail: function (res) {
        wx.showToast({
          title: '系统出错',
          icon: 'none'
        })
      }
    })
  },

  //删除留言
  deleteMessage: function (res) {
    let that = this
    console.log(res.currentTarget.id)
    let item_id = res.currentTarget.id
    wx.showActionSheet({
      itemList: ['删除'],
      success(res) {
        console.log(res.tapIndex)
        if (0 == res.tapIndex) {
          wx.showModal({
            title: '',
            content: '你确定要删除这条留言吗？',
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                MessageDB.doc(item_id).remove({
                  success: function (res) {
                    console.log("删除成功", res)
                    that.onLoad()
                  }, fail: function (res) {
                    console.log("删除出错", res)
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }, fail(res) {
        console.log(res.errMsg)
      }
    })
  },
})